<template>
  <div class="widget-form-noWord widget-form-container">
    <div v-if="data.list.length == 0" class="form-empty">从左侧拖拽来添加字段</div>
    <el-form label-position="top" ref="widget_form_container">
      <draggable class=""
                 v-model="data.list"
                 v-bind="{group:'cmTemplate', ghostClass: 'ghost',animation: 100, handle: '.dragAble'}"
                 @start="onStart"
                 @add="handleWidgetAdd">
        <transition-group name="fade" tag="div" class="widget-form-list">
          <li class="line-width-3" v-for="(element, index) in data.list" :key="element.key">
            <div class="dragAble">
              <widget-form-item v-if="element && element.key"  :element="element" :select.sync="selectWidget" :index="index" :data="data"></widget-form-item>
            </div>
            <div class="form-resize-bar" @mousedown.stop="onmousedown($event, index)" @mouseup="onmouseup">
              <div class="line" style="pointer-events: none;"></div>
            </div>
          </li>
        </transition-group>
      </draggable>
    </el-form>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex'
  import Draggable from 'vuedraggable'
  import WidgetFormItem from './WidgetFormItem'
  import util from '@/utils/util.js'
  export default {
    name: 'widgetFormNoWord',
    components: {
      Draggable,
      WidgetFormItem
    },
    props: ['data', 'select'],
    data () {
      return {
        selectWidget: this.select,
        isOver: false
      }
    },
    computed: {
      ...mapGetters(['hasChoose'])
    },
    watch: {
      select (val) {
        this.selectWidget = val
      },
      selectWidget: {
        handler (val) {
          this.$emit('update:select', val)
        },
        deep: true
      }
    },
    mounted () {
      document.onmouseup = () => {
        document.onmousemove = null
      }
      document.body.ondrop = function (event) {
        let isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1
        if (isFirefox) {
          event.preventDefault()
          event.stopPropagation()
        }
      }
    },
    methods: {
      onStart () {

      },
      dragInto () {
        if (this.hasChoose) {
          this.isOver = true
        }
      },
      dragleave () {
        this.isOver = false
      },
      handleSelectWidget (index) {
        console.log(index, '#####')
        this.selectWidget = this.data.list[index]
      },
      handleWidgetAdd (evt) {
        const newIndex = evt.newIndex
        const to = evt.to
        console.log(to)

        // 为拖拽到容器的元素添加唯一 key
        const key = Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 99999)
        this.$set(this.data.list, newIndex, {
          ...this.data.list[newIndex],
          config: {
            ...this.data.list[newIndex].config,
          },
          key,
          rules: []
        })

        if (this.data.list[newIndex].fieldType === 'radio' || this.data.list[newIndex].fieldType === 'checkbox' || this.data.list[newIndex].fieldType === 'select') {
          this.$set(this.data.list, newIndex, {
            ...this.data.list[newIndex],
            config: {
              ...this.data.list[newIndex].config,
              /*options: this.data.list[newIndex].options.options.map(item => ({
                ...item
              }))*/
            }
          })
        }

        if (this.data.list[newIndex].fieldType === 'grid') {
          this.$set(this.data.list, newIndex, {
            ...this.data.list[newIndex],
            columns: this.data.list[newIndex].columns.map(item => ({...item}))
          })
        }

        /*子表单*/
        if (this.data.list[newIndex].fieldType === 'childForm') {
          this.$set(this.data.list, newIndex, {
            ...this.data.list[newIndex],
            list: [
              {
                childList: this.data.list[newIndex].list.map(item => ({...item})),
                childFormKey: Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 99999)
              }
            ]
          })
        }
        this.selectWidget = this.data.list[newIndex]
      },
      handleWidgetDelete (index) {
        if (this.data.list.length - 1 === index) {
          if (index === 0) {
            this.selectWidget = {}
          } else {
            this.selectWidget = this.data.list[index - 1]
          }
        } else {
          this.selectWidget = this.data.list[index + 1]
        }

        this.$nextTick(() => {
          this.data.list.splice(index, 1)
        })
      },

      onmousedown ($event, index) {
        this.dragBoxWidth = this.$refs.widget_form_container.$el.offsetWidth
        let dragBoxRight = this.$refs.widget_form_container.$el.getBoundingClientRect().right
        let self = this
        let parentBox = $event.target.offsetParent
        let dx = $event.clientX // 当你第一次单击的时候，存储x轴的坐标。
        let dw = parentBox.offsetWidth;//存储默认的div的宽度。
        let disright = parentBox.offsetLeft + parentBox.offsetWidth;//存储div右边距离屏幕左边的距离。
        document.onmousemove = util._throttle(ev => {
          let iEvent = ev || event
          let width = dw + (iEvent.clientX - dx) //iEvent.clientX-dx表示第二次鼠标的X坐标减去第一次鼠标的X坐标，得到绿色移动的距离（为负数），再加上原本的div宽度，就得到新的宽度。
          if (iEvent.clientX > dragBoxRight - 10) return  // 判断是否拖到最右边
          parentBox.style.width = width + 'px'
          self.data.list[index].config.width = Number(width / self.dragBoxWidth * 100).toFixed(2) + '%'
        })
        return false;
      },
      onmouseup () {
        document.onmousedown=null;
        document.onmousemove=null;
      }
    }
  }
</script>

<style lang="scss">
  .widget-form-noWord.widget-form-container {
    position: static;
    .dragBox {
      /*&.forbidden-childe-pointer-events * {
        pointer-events: none;
      }*/
    }
    .widget-form-list {
      display: flex;
      flex-wrap: wrap;
      align-content: flex-start;
      margin: 0;
      li {

        list-style-type:none;
        position: relative;
        .form-resize-bar {
          position: absolute;
          top: 0;
          right: 0;
          bottom: 0;
          width: 12px;
          cursor: ew-resize;
          &:hover{
            .line {
              display: block;
            }
          }
          .line {
            position: absolute;
            top: 5px;
            right: 3px;
            width: 2px;
            height: calc(100% - 10px);
            background-color: #409EFF;
            display: none;
          }
        }
      }
      .line-width-3 {
        width: calc(33.3% - 1px);
        &:nth-child(3n+3) {

        }
      }
      .dragAble {
        .widget-view {
          margin: 5px;
          padding: 10px;
          box-sizing: border-box;
          border: none;
          background-color: rgba(236, 245, 255, 0.3);
          &.active {
            background-color: #ecf5ff;
            border: none;
            outline: none;
          }
          &:hover {
            background-color: #ecf5ff;
            border: none;
            outline: none;
          }
          .el-form-item__label {
            background-color: rgba(0,0,0,0);
          }
          .el-form-item__content {
            width: 100%;
          }
          .widget-view-action {
            top: 15px;
            display: flex;
            background: #fff;
            box-shadow: 0px 2px 4px 0px #ddd;
            border-radius: 24px;
            align-items: center;
            right: 5px;
            height: 25px;
            .btn-copy, .btn-delete {
              padding: 0 5px;
              cursor: pointer;
              font-size: 14px;
              height: 25px;
              line-height: 25px;
              text-align: center;
              color: #91a1b7;
              background-color: transparent;
              margin: 0;
            }
            .btn-copy {
              border-radius: 12px 0 0 12px;
              &:hover{
                color: #248AF9;
                background-color: #b7e6fe;
              }
            }
            .btn-delete {
              border-radius: 0 12px 12px 0;
              &:hover {
                color: #d84636;
                background-color: #FDECEC;
              }
            }
          }
        }
      }
    }
  }
</style>
